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name;
	var _time;
}

var User_Play = [
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
];

var focus_num=0;          //사각사각로직 포커스
var Complete=0;           
var timer;                //시간잴대 타이머
var P_INTERVAL=10;        //타이머의 보여질 시간
var timmerId;             //타이머의 ID
var arrTime=new Array();  //시간이 기록되는 배열
var topc= 132;		//가로의 위아래 컨트롤
var leftc= 580;		//세로의 왼쪽오른쪽 컨트롤

var match_width = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var match_height= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var x =0;
var y =0;
var sagak_min = 20; // 
var sagak_sec = sagak_min * 60 ; //
var timerchecker = null; //
var curTime;
var pauseFlag=0;
var popEXIT=0;
var yEXIT=0;
var popBefore=0;
var yBefore=0;
var popGameOver=0;
var popStageClear=0;


var _topscore = new Array();		// 스코어 저장하기 위한 배열

var stage = 0;   	// 스테이지

var timeupitem=3;
var hintitem=3;

var stageState=[0, 0, 0, 0, 0];

var Input  = function(id, previousId, nextId)
{
	var ime;
	
	
    var imeReady = function(imeObject)
	{
		imeObject.modeArr = ['_kor','_latin_small','_latin_big','_num','_special'];
        installStatusCallbacks();
        Main.ready(id);
    }
	
		ime = new IMEShell(id, imeReady,'en');

    
    var element = document.getElementById( id );
    var previousElement = document.getElementById(previousId);
    var nextElement = document.getElementById(nextId);


    var installStatusCallbacks = function()
    { 
        ime.setKeypadPos(650, 80);
        ime.setWordBoxPos(18, 6);
		ime.setBlockSpace (true);
    }
    
    
}


var Main =
{
    elementIds : ["inputName"],
    inputs : [ null ],
    ready : [ false]
}

Main.createInputObjects = function()
{
    
    for (var index in this.elementIds)
    {
        
        var previousIndex = index - 1;
        if (previousIndex < 0)
        {   
            previousIndex = this.inputs.length - 1;
        }
        var nextIndex = (index + 1) % this.inputs.length;
        
        this.inputs[index] = new Input( this.elementIds[index], this.elementIds[previousIndex], this.elementIds[nextIndex] );
        
    }
    
   
}


Main.ready = function(id)
{
    ready = true;
     
    for (var i in Main.elementIds)
    {
        if (Main.elementIds[i] == id)
        {
            Main.ready[i] = true;
        }
        
        if (Main.ready[i] == false)
        {
            ready = false;
        }
    }
    

}

var str1;
Main.onLoad = function()
{

	$("#ready").animate({left:50}, "slow");  
		//document.getElementById('minUP').style.visibility="visible"; 
	$("#ready").animate({left:300}, "slow");
	document.getElementById('ready').style.visibility="visible";
	$("#ready").fadeOut("slow"); 
	
	if(location.search){
		str1=location.search.split("@")[0];
		stage=location.search.split("@")[1];
	}
	
	for(i = 0; i < 15; i++) {
		for(j = 0; j < 15; j++) {
			item[i][j] = Map[stage][i][j];
		}
	}
	
	// Set Default key handler function
	  pluginAPI.registIMEKey();
	 widgetAPI.sendReadyEvent();
	 pluginIME = document.getElementById("pluginIME");	
	  window.onShow = Main.initKeys; 
	sagakTimer();
	 $("#focus0").focus();
	 $("#focus0").css({borderColor:'red', borderStyle:'solid',borderWidth:'1px'});	     
	 
	 SetIndex();   
	 
	 Main.createInputObjects();

	 initTopScore();
	 readTopScore(stage);	// stage 0일때
	 addTopScore();
	 setItem(timeupitem,hintitem);
	 
	Player.init();
	 Audio.init();
}

Main.onUnload = function()
{
	 Player.deinit();
}
function sound_effect(name)
{
			Player.stopVideo();
			var videoURLs = [ ];
			videoURLs="$WIDGET/sound/"+name+".wav";
			//get URL
			Player.setVideoURL(videoURLs);	//path modify!!
		
			Player.playVideo();
}

function SetIndex()
{
	for(i=0;i<15;i++) {
		var inHTML_W = "<div valign=bottom align=center><font color='COLOR'>";
		if(match_width[i] == 1)
			inHTML_W = inHTML_W.replace("COLOR", "gray");
		else
			inHTML_W = inHTML_W.replace("COLOR", "black");
		var state = -1; //0:네모 없는 곳, 1 : 네모 있는 곳
		var countnum = 0;
		for(j=0;j<15;j++){
			
			if(state == 1 && Map[stage][j][i] == 0) {
				inHTML_W += countnum + "<br>";
				document.getElementById("text_width"+i).innerHTML = inHTML_W;
				state = 0;
				countnum = 0;
			}
			else if(Map[stage][j][i] == 1) {
				state = 1;
				countnum++;
			}
		}
		if(state == 1)
			inHTML_W += countnum + "<br>";
		else if(state == -1)
			inHTML_W += "<div valign=bottom align=center><font color='gray'>0<br>";
		inHTML_W += "</font></div>"
		document.getElementById("text_width"+i).innerHTML = inHTML_W;
	 }
	 
	 for(i=0;i<15;i++) {
		var inHTML_H = "<div align=right><font color='COLOR'>";
		if(match_height[i] == 1)
			inHTML_H = inHTML_H.replace("COLOR", "gray");
		else
			inHTML_H = inHTML_H.replace("COLOR", "black");
		var state = -1;
		var countnum = 0;
		for(j=0;j<15;j++){
			if(state == 1 && Map[stage][i][j] == 0) {
				inHTML_H += countnum + "&nbsp;&nbsp;&nbsp;";
				document.getElementById("text_height"+i).innerHTML = inHTML_H;
				state = 0;
				countnum = 0;
			}
			else if(Map[stage][i][j] == 1) {
				state = 1;
				countnum++;
			}
		}
		if(state == 1)
			inHTML_H += countnum + "&nbsp;&nbsp;&nbsp;";
		else if(state == -1)
			inHTML_H += "<div align=right><font color='gray'>0&nbsp;&nbsp;&nbsp;";
		inHTML_H += "</font></div>"
		document.getElementById("text_height"+i).innerHTML = inHTML_H;
	 }
	
}


function Clock()
{
             var time = new Date();
             document.form1.txtClock.value = time.getHours() + " : " + time.getMinutes() + " : " + time.getSeconds();
             timer = setTimeout("Clock()", 1000);//1초마다 Clock함수를 호출.
}

 

function Stop()
{

             clearTimeout(timer);

}


sagakTimer=function()
 {
  r_min = parseInt(sagak_sec / 60);
  r_sec = sagak_sec % 60;
  if(sagak_sec > 0){
     
   switch(r_min){
   
   case 26:
            document.getElementById('min').src="resource/time/26m.png"; break;
			
   case 25:
            document.getElementById('min').src="resource/time/25m.png"; break;
 
   case 24:
            document.getElementById('min').src="resource/time/24m.png"; break;
   
   case 23:
            document.getElementById('min').src="resource/time/23m.png"; break;
   
   case 22:
            document.getElementById('min').src="resource/time/22m.png"; break;
   
   case 21:
            document.getElementById('min').src="resource/time/21m.png"; break;
		
	
   case 20:
            document.getElementById('min').src="resource/time/20m.png"; break;
			
   case 19:
            document.getElementById('min').src="resource/time/19m.png"; break;
 
   case 18:
            document.getElementById('min').src="resource/time/18m.png"; break;
   
   case 17:
            document.getElementById('min').src="resource/time/17m.png"; break;
   
   case 16:
            document.getElementById('min').src="resource/time/16m.png"; break;
   
   case 15:
            document.getElementById('min').src="resource/time/15m.png"; break;
   
   case 14:
            document.getElementById('min').src="resource/time/14m.png"; break;
   
   case 13:
            document.getElementById('min').src="resource/time/13m.png"; break;
   
   case 12:
            document.getElementById('min').src="resource/time/12m.png"; break;
   
    case 11:
            document.getElementById('min').src="resource/time/11m.png";
   break;
   
    case 10:
            document.getElementById('min').src="resource/time/10m.png";
   break;
   
    case 9:
            document.getElementById('min').src="resource/time/09m.png";
   break;
   
    case 8:
            document.getElementById('min').src="resource/time/08m.png";
   break;
   
    case 7:
            document.getElementById('min').src="resource/time/07m.png";
   break;
   
    case 6:
            document.getElementById('min').src="resource/time/06m.png";
   break;
   
    case 5:
            document.getElementById('min').src="resource/time/05m.png";
   break;
   
    case 4:
            document.getElementById('min').src="resource/time/04m.png";
   break;
   
    case 3:
            document.getElementById('min').src="resource/time/03m.png";
   break;
   
    case 2:
            document.getElementById('min').src="resource/time/02m.png";
   break;
   
    case 1:
            document.getElementById('min').src="resource/time/01m.png";
   break;
   
    case 0:
            document.getElementById('min').src="resource/time/00m.png";
   break;
     
   }
   
    switch(r_sec){
   
   case 0:
            document.getElementById('sec').src="resource/time/00s.png";
   break;
   
    case 59:
            document.getElementById('sec').src="resource/time/59s.png";
   break;
   
    case 58:
            document.getElementById('sec').src="resource/time/58s.png";
   break;
   
    case 57:
            document.getElementById('sec').src="resource/time/57s.png";
   break;
   
    case 56:
            document.getElementById('sec').src="resource/time/56s.png";
   break;
   
    case 55:
            document.getElementById('sec').src="resource/time/55s.png";
   break;
   
    case 54:
            document.getElementById('sec').src="resource/time/54s.png";
   break;
   
    case 53:
            document.getElementById('sec').src="resource/time/53s.png";
   break;
   
    case 52:
            document.getElementById('sec').src="resource/time/52s.png";
   break;
   
    case 51:
            document.getElementById('sec').src="resource/time/51s.png";
   break;
   
    case 50:
            document.getElementById('sec').src="resource/time/50s.png";
   break;
   
    case 49:
            document.getElementById('sec').src="resource/time/49s.png";
   break;
   
    case 48:
            document.getElementById('sec').src="resource/time/48s.png";
   break;
   
    case 47:
            document.getElementById('sec').src="resource/time/47s.png";
   break;
   
    case 46:
            document.getElementById('sec').src="resource/time/46s.png";
   break;
   
    case 45:
            document.getElementById('sec').src="resource/time/45s.png";
   break;
   
    case 44:
            document.getElementById('sec').src="resource/time/44s.png";
   break;
   
    case 43:
            document.getElementById('sec').src="resource/time/43s.png";
   break;
   
    case 42:
            document.getElementById('sec').src="resource/time/42s.png";
   break;
   
    case 41:
            document.getElementById('sec').src="resource/time/41s.png";
   break;
   
    case 40:
            document.getElementById('sec').src="resource/time/40s.png";
   break;
   
    case 39:
            document.getElementById('sec').src="resource/time/39s.png";
   break;
   
    case 38:
            document.getElementById('sec').src="resource/time/38s.png";
   break;
   
    case 37:
            document.getElementById('sec').src="resource/time/37s.png";
   break;
   
    case 36:
            document.getElementById('sec').src="resource/time/36s.png";
   break;
   
    case 35:
            document.getElementById('sec').src="resource/time/35s.png";
   break;
   
    case 34:
            document.getElementById('sec').src="resource/time/34s.png";
   break;
   
    case 33:
            document.getElementById('sec').src="resource/time/33s.png";
   break;
   
    case 32:
            document.getElementById('sec').src="resource/time/32s.png";
   break;
   
    case 31:
            document.getElementById('sec').src="resource/time/31s.png";
   break;
   
    case 30:
            document.getElementById('sec').src="resource/time/30s.png";
   break;
   
    case 29:
            document.getElementById('sec').src="resource/time/29s.png";
   break;
   
    case 28:
            document.getElementById('sec').src="resource/time/28s.png";
   break;
   
    case 27:
            document.getElementById('sec').src="resource/time/27s.png";
   break;
   
    case 26:
            document.getElementById('sec').src="resource/time/26s.png";
   break;
   
    case 25:
            document.getElementById('sec').src="resource/time/25s.png";
   break;
   
    case 24:
            document.getElementById('sec').src="resource/time/24s.png";
   break;
   
    case 23:
            document.getElementById('sec').src="resource/time/23s.png";
   break;
   
    case 22:
            document.getElementById('sec').src="resource/time/22s.png";
   break;
   
    case 21:
            document.getElementById('sec').src="resource/time/21s.png";
   break;
   
    case 20:
            document.getElementById('sec').src="resource/time/20s.png";
   break;
   
    case 19:
            document.getElementById('sec').src="resource/time/19s.png";
   break;
   
    case 18:
            document.getElementById('sec').src="resource/time/18s.png";
   break;
   
    case 17:
            document.getElementById('sec').src="resource/time/17s.png";
   break;
   
    case 16:
            document.getElementById('sec').src="resource/time/16s.png";
   break;
   
    case 15:
            document.getElementById('sec').src="resource/time/15s.png";
   break;
   
    case 14:
            document.getElementById('sec').src="resource/time/14s.png";
   break;
   
    case 13:
            document.getElementById('sec').src="resource/time/13s.png";
   break;
   
    case 12:
            document.getElementById('sec').src="resource/time/12s.png";
   break;
   
    case 11:
            document.getElementById('sec').src="resource/time/11s.png";
   break;
   
    case 10:
            document.getElementById('sec').src="resource/time/10s.png";
   break;
   
    case 9:
            document.getElementById('sec').src="resource/time/09s.png";
   break;
   
    case 8:
            document.getElementById('sec').src="resource/time/08s.png";
   break;
   
    case 7:
            document.getElementById('sec').src="resource/time/07s.png";
   break;
   
    case 6:
            document.getElementById('sec').src="resource/time/06s.png";
   break;
   
    case 5:
            document.getElementById('sec').src="resource/time/05s.png";
   break;
   
    case 4:
            document.getElementById('sec').src="resource/time/04s.png";
   break;
   
    case 3:
            document.getElementById('sec').src="resource/time/03s.png";
   break;
   
    case 2:
            document.getElementById('sec').src="resource/time/02s.png";
   break;
   
    case 1:
            document.getElementById('sec').src="resource/time/01s.png";
   break;
     
   }   
   
   if(sagak_sec > 0 && pauseFlag==0){
   sagak_sec--;
   timerchecker = setTimeout("sagakTimer()", 900); 
   }
  } 
  else { //
   
   clearTimeout(timerchecker);
   document.getElementById('gameover').style.visibility="visible";
   popGameOver=1;
   /*진성진성*/
  }
 }

/////////////////////////////////

function startWatch(obj){ //워치시작

  arrTime.length=0;
  
  arrTime[++arrTime.length-1]=new Date();

  document.myform.txtTimer.value=document.myform.txtTimer.defaultValue;

  timmerId = setInterval('timmer()', P_INTERVAL); //timmer함수를 P_INTERVAL 간격으로 호출함
  
  //document.getElementById('result').innerHTML='';
  
  //showResult(obj.value);

}


function checkWatch(obj){ //중간중간 기록체크

  arrTime[++arrTime.length-1]=new Date();
  
  showResult(obj.value);
}

function stopWatch(obj){ //스탑워치 종료함

  arrTime[++arrTime.length-1]=new Date();

  clearInterval(timmerId);

  showResult(obj.value);
}

function timmer(){

  var strElapTime  = getElapTime(arrTime[0],new Date());

  document.myform.txtTimer.value=strElapTime;

}


function showResult(strMessage){ //중간중간 스탑워치 기록

  var time = arrTime[arrTime.length-1].toLocaleString();

  var msec = arrTime[arrTime.length-1].getMilliseconds();

  var strElapTime  = getElapTime(arrTime[0],arrTime[arrTime.length-1]);
 
  //document.getElementById('result').innerHTML+=time+'.'+getFixStr(msec,3,0)+' :: elapsed time is '+strElapTime+' '+strMessage+'<br>';

  if(strMessage=="종료") document.myform.txtTimer.value=strElapTime;
}



function getFixStr(strSrc,nLen,strAdd,isFront) { //문자 길이만큼 반환

  strSrc = (strSrc==null)?"" :""+strSrc;
  
  strAdd = (strAdd==null)?" ":""+strAdd;
  
  var nLenBase = strSrc.length;
  
  for(var i=0;i<nLen-nLenBase;i++)
    strSrc = (isFront)?strAdd+strSrc:strSrc+strAdd;
  
  return strSrc;
}

function getElapTime(startTime, endTime){ //시간차이계산해서 경과시간 반환

  var elapTime = new Date();
  
  elapTime.setTime(endTime-startTime);
  
  return getFixStr(elapTime.getUTCHours(),2,0,true)+':'+getFixStr(elapTime.getMinutes(),2,0,true)+':'+getFixStr(elapTime.getSeconds(),2,0,true)+'.'+getFixStr(elapTime.getMilliseconds(),3,0,true);
}


Main.MainKeyHandler = function()
{
	var KeyCode = event.keyCode;

	
	
	$("#focus"+focus_num).css({borderColor:'black', borderStyle:'solid',borderWidth:'1px'});
	switch(KeyCode)
	{
		 
		case tvKey.KEY_LEFT :
		
		//////////////////////////진성
		if(popEXIT==1){
		document.getElementById('popEXIT').src="resource/popup/exit_y.png";
		yEXIT=1;
		break;
		}
		
		if(popBefore==1){
		document.getElementById('before').src="resource/popup/before_y.png";
		yBefore=1;
		break;
		}
		
		if(pauseFlag==1){ 
		alert("포커스못감");
		break;
		}
	//////////////////////////	
		
		
		
		focus_num-=1;
		if(focus_num<0) //0보다작아질때가 언제야ㅋㅋㅋㅋ대체
			focus_num+=1;
		
			///////////////////////
		leftc-=23;
		if(focus_num==0)
		leftc=580;
		else if(focus_num%15==14)
		{
		leftc=580+23*14;
		topc-=22;
		}
		$("#sero").css("left",leftc );
		$("#garo").css("top",topc );
		
			break;
            
		case tvKey.KEY_RIGHT :
		
		//////
		if(popEXIT==1){
		document.getElementById('popEXIT').src="resource/popup/exit_n.png";
		yEXIT=0;
		break;
		}
		
		if(popBefore==1){
		document.getElementById('before').src="resource/popup/before_n.png";
		yBefore=0;
		break;
		}

		if(pauseFlag==1) { 
		alert("포커스못감");
		break;
		}
		////////
		
		
		focus_num+=1;
		if(focus_num>224)
			focus_num-=1;
		
		//세로의 움직임... 그리고 가로도
		leftc+=23;
		if(focus_num==224)
		leftc=580+23*14;
		else if(focus_num%15==0)
		{
		leftc=580;
		topc+=22;
		}
		$("#sero").css("left",leftc );
		$("#garo").css("top",topc );
			break;
		case tvKey.KEY_UP :
		
		if(pauseFlag==1) { 
		alert("포커스못감");
		break;
		}
		
		focus_num-=15;
		if(focus_num<0)
			focus_num+=15;
		
		//가로의 움직임...
		topc-=22;
		if(focus_num<=14)
		topc=132;
		
		$("#garo").css("top",topc );
			break;
		case tvKey.KEY_DOWN :
		
		if(pauseFlag==1) { 
		alert("포커스못감");
		break;
		}
		
		focus_num+=15;
		if(focus_num>224)
			focus_num-=15;
		
		//가로의 움직임...
		topc+=22;
		if(focus_num>=210)
		topc=132+22*14;
		
		$("#garo").css("top",topc );
			break;
		case tvKey.KEY_ENTER :	//////////////////진성진성
		
		if(popStageClear==1) { 
			checkScore($("#inputName").val(),sagak_sec);
			writeTopScore(stage);
			window.close();
			window.open("stage.html?temp="+str1,"logic","width=960,height=540");
		}
		
		if(popBefore==1){
		
		if(yBefore==1){ //복귀하시겠는가 예일때		
			///////////////
			//sound_effect("select");
			///////////////
			window.close();
			window.open("stage.html?temp="+str1,"logic","width=960,height=540");
		
		} else if(yBefore==0){ //아니오일때		
			///////////////
			sound_effect("select");
			///////////////
		document.getElementById('before').style.visibility="hidden";
		popBefore=0;
		pauseFlag=0;
		sagak_sec = curTime; //아까저장했던 시간
		sagakTimer(); //시간을 다시 이어서 구동시키세		
		}			
		break; 
		}
		
		if(popGameOver==1){ //게임오버~	
			window.close();
			window.open("15x15.html?temp="+window.location.search,"logic","width=960,height=540");	
		}
				
		if(popEXIT==1){
			
		
		if(yEXIT==1){ //종료하시겠는가 예일때		
		widgetAPI.sendReturnEvent();		//스마트허브로 나가자
		} else if(yEXIT==0){ //아니오일때		
			///////////////
			sound_effect("select");
			///////////////
		document.getElementById('popEXIT').style.visibility="hidden";
		popEXIT=0;
		pauseFlag=0;
		sagak_sec = curTime; //아까저장했던 시간
		sagakTimer(); //시간을 다시 이어서 구동시키세		
		}			
		break; 
		}
		
		if(pauseFlag==1) { 
		alert("포커스못감");
		break;
		}
		///////////////////		
			//play the game...visual state modify
			if(focus_num<15)
			{
				if(Map[stage][0][focus_num] == 1 && User_Play[0][focus_num]==0)	// 비어있을때 잘 선택하면
				{
					User_Play[0][focus_num]=1;
					item[0][focus_num]=0;
					$("#focus"+focus_num).attr("background","resource/15x15/Ocheck.png");
					///////////////
					//sound_effect("ok");
					///////////////
					
					var MapTrueCount = 0;
					var UserTrueCount = 0;
					
					for(i=0; i<15; i++) {
						if(Map[stage][0][i] == 1)
							MapTrueCount++;
						if(User_Play[0][i] == 1)
							UserTrueCount++;
					}
					if(MapTrueCount == UserTrueCount)
						match_height[0] = 1;
						
					
					MapTrueCount = 0;
					UserTrueCount = 0;
					
					for(i=0; i<15; i++) {
						if(Map[stage][i][focus_num] == 1)
							MapTrueCount++;
						if(User_Play[i][focus_num] == 1)
							UserTrueCount++;
					}
					if(MapTrueCount == UserTrueCount)
						match_width[focus_num] = 1;
						
					SetIndex();
				}
				
				else if((Map[stage][0][focus_num] == 0)&&( User_Play[0][focus_num]==0 || User_Play[0][focus_num]==3))	// 비어있거나 빨간 x일때 잘못 선택하면 
				{
					User_Play[0][focus_num]=3;
					$("#focus"+focus_num).attr("background","resource/15x15/Xred.png");
					///////////////
					//sound_effect("no");
					///////////////
					
				//시간깎기 및 이펙트
				$("#minDOWN").fadeTo("slow",0.6);  
				//$("#minDOWN").animate({left:0}, "slow");  
				//$("#minDOWN").animate({top:-500}, "slow");
				document.getElementById('minDOWN').style.visibility="visible"; $("#minDOWN").fadeOut("slow");  
				sagak_sec = sagak_sec - 120; //2분 증가
				//////////////
					
				}
				
				else if(User_Play[0][focus_num] == 2)	// x일때 선택하면
				{
					User_Play[0][focus_num]=0;
					$("#focus"+focus_num).attr("background","resource/15x15/nothing.png");
				}
				
			}
			else
			{
				if(Map[stage][Math.floor(focus_num/15)][focus_num%15] == 1 && User_Play[Math.floor(focus_num/15)][focus_num%15]==0)
				{
					User_Play[Math.floor(focus_num/15)][focus_num%15]=1;
					item[Math.floor(focus_num/15)][focus_num%15]=0;
					$("#focus"+focus_num).attr("background","resource/15x15/Ocheck.png");
					///////////////
					//sound_effect("ok");
					///////////////
					
					var MapTrueCount = 0;
					var UserTrueCount = 0;
					
					for(i=0; i<15; i++) {
						if(Map[stage][Math.floor(focus_num/15)][i] == 1)
							MapTrueCount++;
						if(User_Play[Math.floor(focus_num/15)][i] == 1)
							UserTrueCount++;
					}
					if(MapTrueCount == UserTrueCount)
						match_height[Math.floor(focus_num/15)] = 1;
						
					
					MapTrueCount = 0;
					UserTrueCount = 0;
					
					for(i=0; i<15; i++) {
						if(Map[stage][i][focus_num%15] == 1)
							MapTrueCount++;
						if(User_Play[i][focus_num%15] == 1)
							UserTrueCount++;
					}
					if(MapTrueCount == UserTrueCount)
						match_width[focus_num%15] = 1;
						
					SetIndex();
				}
				
				else if((Map[stage][Math.floor(focus_num/15)][focus_num%15] == 0) && (User_Play[Math.floor(focus_num/15)][focus_num%15]==0 || User_Play[Math.floor(focus_num/15)][focus_num%15]==3))
				{
					User_Play[Math.floor(focus_num/15)][focus_num%15]=3;
					$("#focus"+focus_num).attr("background","resource/15x15/Xred.png");
					///////////////
					//sound_effect("no");
					///////////////
					//시간깎기 및 이펙트
				$("#minDOWN").fadeTo("slow",0.6);  
				//$("#minDOWN").animate({left:0}, "slow");  
				//$("#minDOWN").animate({top:-500}, "slow");
				document.getElementById('minDOWN').style.visibility="visible"; $("#minDOWN").fadeOut("slow");  
				sagak_sec = sagak_sec - 120; //2분 증가
				//////////////
				}
				
				else if(User_Play[Math.floor(focus_num/15)][focus_num%15] == 2)
				{
					User_Play[Math.floor(focus_num/15)][focus_num%15]=0;
					$("#focus"+focus_num).attr("background","resource/15x15/nothing.png");
				}
				
			}
			//alert("test!!!!"+Map[stage][i*10+j]);
			//check the complete
			stageClear();
			
			break;
			
		case tvKey.KEY_RED	:
		
		if(pauseFlag==1) { 
		alert("포커스못감");
		break;
		}
		   
			if(focus_num<15)
			{
				if(User_Play[0][focus_num]==2)
				{
					User_Play[0][focus_num]=0;
					$("#focus"+focus_num).attr("background","resource/15x15/nothing.png");
				}
				else if(User_Play[0][focus_num] == 0)
				{
					User_Play[0][focus_num]=2;
					$("#focus"+focus_num).attr("background","resource/15x15/Xcheck.png");
					///////////////
					//sound_effect("x");
					///////////////
				}
			}
			else
			{
				if(User_Play[Math.floor(focus_num/15)][focus_num%15]==2)
				{
					User_Play[Math.floor(focus_num/15)][focus_num%15]=0;
					$("#focus"+focus_num).attr("background","resource/15x15/nothing.png");
				}
				else if(User_Play[Math.floor(focus_num/15)][focus_num%15] == 0)
				{
					User_Play[Math.floor(focus_num/15)][focus_num%15]=2;
					$("#focus"+focus_num).attr("background","resource/15x15/Xcheck.png");
					///////////////
					//sound_effect("x");
					///////////////
				}
			}
			break;
			
		case tvKey.KEY_BLUE	: /////////////힌트 뿌려주는것
		//////////////////////////////진성진성
		var random_index;
		var num;
		var find;
		/* 개발자 모드 */
		/*
			document.getElementById('complete').style.visibility="visible";
			document.getElementById("completeSec").innerHTML = "기록:"+ parseInt(sagak_sec/60)+"분"+sagak_sec%60+"초";
			document.getElementById('inputName').style.visibility="visible";
			$("#inputName").focus();
			popStageClear=1;
			pauseFlag=1;
			setClearImage(stage);
			setStageName(stage);
			writeFile(stage);
		*/
		
		if(pauseFlag==1) { 
		alert("포커스못감");
		break;
		}
		alert("랜덤블루작동");
		if(!(hintitem == 0))
		{
			///////////////
			sound_effect("hint");
			///////////////
		for (x = 0; x < 15; x++){			  			
			for (y = 0; y < 15; y++){
				if(item[x][y]==1)
				{	//아직 유저가 못찾아낸 답이구나
					User_Play[x][y]=1;
					item[x][y]=0;
					num= (x*15)+y;
					$("#focus"+num).attr("background","resource/15x15/Ocheck.png");
					
					find=1;
					$("#hint").fadeTo("slow",0.6); 
					//$("#minDOWN").animate({left:0}, "slow");  
					//$("#minDOWN").animate({top:-500}, "slow");
					document.getElementById('hint').style.visibility="visible"; $("#hint").fadeOut("slow");
					
					var MapTrueCount = 0;
					var UserTrueCount = 0;
					
					for(i=0; i<15; i++) {
						if(Map[stage][x][i] == 1)
							MapTrueCount++;
						if(User_Play[x][i] == 1)
							UserTrueCount++;
					}
					if(MapTrueCount == UserTrueCount)
						match_height[x] = 1;
						
					MapTrueCount = 0;
					UserTrueCount = 0;
					
					for(i=0; i<15; i++) {
						if(Map[stage][i][y] == 1)
							MapTrueCount++;
						if(User_Play[i][y] == 1)
							UserTrueCount++;
					}
					if(MapTrueCount == UserTrueCount)
						match_width[y] = 1;
					
					SetIndex(); //다되면 회색글시로 바껴야 하는데...
					
					stageClear(); //마지막 남은 한칸을 힌트로 맞출수도 있으므로  스테이지 클리어 확인.
					break;   
				}				
			}
			
				if(find==1) break;
		}
		setItem(timeupitem,--hintitem);
		}
		else
		{
			///////////////
			sound_effect("itemno");
			///////////////
					
		}
		break;
        ////////////////// //////////////////////////힌트끝  
            
        case tvKey.KEY_YELLOW: //timeUp기능 타임업이펙트보여주고 시간 120초 증가
		
		//////////////////////////////////
		if(pauseFlag==1) { 
		alert("포커스못감");
		break;
		}
		if(!(timeupitem == 0))
		{			
			///////////////
			sound_effect("time");
			///////////////
		$("#minUP").animate({top:300}, "slow");  
		//document.getElementById('minUP').style.visibility="visible"; 
		$("#minUP").animate({top:-500}, "slow");
		document.getElementById('minUP').style.visibility="visible";
		sagak_sec = sagak_sec + 120; //2분 증가
		setItem(--timeupitem,hintitem);
		}
		else
		{
			///////////////
			sound_effect("itemno");
			///////////////
		}
        ///////////////////////////////////////////
		
        break;
		
		case tvKey.KEY_GREEN:
		
		if(pauseFlag==1) { 
			window.close();
			window.open("15x15.html?temp="+window.location.search,"logic","width=960,height=540");
		}
		
		else if(popStageClear==1) { 
			window.close();
			window.open("15x15.html?temp="+window.location.search,"logic","width=960,height=540");
		}
		
		
		break;
		
		
		case tvKey.KEY_PAUSE:
		
			if(popStageClear == 1)
			{
			
			}
			else
			{
			///////////////
			sound_effect("pause");
			///////////////
			alert("이건pause키");
			
			if(pauseFlag==0) { //정지
			
			curTime = sagak_sec; //pause상태될때의 마지막시간을 저장
			pauseFlag=1; //멈췃을때는 더이상 1초마다 시간카운트 되지않게 위에서 조절
			$("#pause").fadeIn("slow");
			document.getElementById('pause').style.visibility="visible";
			
			}else{ //팝업없애주기
			
			pauseFlag=0;
			sagak_sec = curTime;
			$("#pause").fadeOut("slow");
			document.getElementById('pause').style.visibility="hidden";
			sagakTimer(); //시간을 다시 이어서 구동시키세		
			}
			}
		
		break;
        
        
        case tvKey.KEY_RETURN:
			///////////////
			sound_effect("pause");
			///////////////
			widgetAPI.blockNavigation(event);
            //stopWatch(this); //	
			if(popStageClear == 1)
			{
			}
			else
			{
				if(popGameOver==1){ //게임오버~
					window.close();
					window.open("stage.html?temp="+str1,"logic","width=960,height=540");
				}
				
				if(popEXIT==1) {
				document.getElementById('popEXIT').style.visibility="hidden";
				popEXIT=0;
				pauseFlag=0;
				sagak_sec = curTime;
				sagakTimer(); //시간을 다시 이어서 구동시키세		
				break;
				}
				
				if(popBefore==1) {
				document.getElementById('before').style.visibility="hidden";
				popBefore=0;
				pauseFlag=0;
				sagak_sec = curTime;
				sagakTimer(); //시간을 다시 이어서 구동시키세		
				break;
				}
				
				document.getElementById('before').style.visibility="visible";
				popBefore=1;
				curTime = sagak_sec; //잠시 시간 정지를 위해  마지막시간을 저장
				pauseFlag=1; //멈췃을때는 더이상 1초마다 시간카운트 되지않게 위에서 조절
			}
        break;
        
        case tvKey.KEY_EXIT:
			///////////////
			sound_effect("pause");
			///////////////
			widgetAPI.blockNavigation(event);
			if(popStageClear == 1)
			{
			}
			else
			{
			document.getElementById('popEXIT').style.visibility="visible"; //기본적으로 포커스는 아니오에..
			popEXIT=1;		
			curTime = sagak_sec; //잠시 시간 정지를 위해  마지막시간을 저장
			pauseFlag=1; //멈췃을때는 더이상 1초마다 시간카운트 되지않게 위에서 조절
			}
        break;    
			
		default :
			break;
	}
	 $("#focus"+focus_num).css({borderColor:'red', borderStyle:'solid',borderWidth:'1px'});
}

/////진성
function stageClear(){ //힌트썼을때도 스테이지 클리어확인, 유저가 직접 맞출때도 각각 호출된디

			var i=0;
			var j=0;
			/* 퍼즐을 다 맞췄는지 판별하는 아이 */
			 for (i = 0; i < 15; i++)
			 {			  
				for (j = 0; j < 15; j++)
				{
					
					if(  Map[stage][i][j]==1  )
					{	
						if(User_Play[i][j]==1)
						{	
							Complete=1;
						}
						else
						{
							Complete=0;
							i = 15;
							break;
						}
					}
								
				}
			}
		
		if(Complete==1)
		{	
			///////////////
			sound_effect("end");
			///////////////
			document.getElementById('complete').style.visibility="visible";
			document.getElementById("completeSec").innerHTML = "기록:"+ parseInt(sagak_sec/60)+"분"+sagak_sec%60+"초";
			document.getElementById('inputName').style.visibility="visible";
			$("#inputName").focus();
			popStageClear=1;
			pauseFlag=1;
			setClearImage(stage);
			setStageName(stage);
			writeFile(stage);
		}


}


////// 수진 Topscore 구현

function initTopScore()
{
	for(var i=0;i<3;i++)
	{
		_topscore[i] = new Topscore();
		_topscore[i]._name = "";
		_topscore[i]._time = 0;
	}
	
	for(var i=1;i<=3;i++)
	{
		document.getElementById("scorenum" + i).innerHTML = i + ".";
	}
}


function addTopScore()
{
	if(!(_topscore[0]._time == 0))	
	{
		document.getElementById("scorename1").innerHTML = _topscore[0]._name;
		document.getElementById("score1").innerHTML = parseInt(_topscore[0]._time/60) + " : " + _topscore[0]._time%60;
	}
	if(!(_topscore[1]._time == 0))	
	{
		document.getElementById("scorename2").innerHTML = _topscore[1]._name;
		document.getElementById("score2").innerHTML = parseInt(_topscore[1]._time/60) + " : " + _topscore[1]._time%60;
	}
	if(!(_topscore[2]._time == 0))	
	{
		document.getElementById("scorename3").innerHTML = _topscore[2]._name;
		document.getElementById("score3").innerHTML = parseInt(_topscore[2]._time/60) + " : " + _topscore[2]._time%60;
	}
}


checkScore = function(name,score)
{

	if(_topscore[0]._time<score) 
	{
	
		_topscore[2]._name = _topscore[1]._name;
		_topscore[2]._time = _topscore[1]._time;
		
		_topscore[1]._name = _topscore[0]._name;
		_topscore[1]._time = _topscore[0]._time;
	
		_topscore[0]._name = name;
		_topscore[0]._time = score;
	}
	
	else if(_topscore[1]._time<score)
	{
		_topscore[2]._name = _topscore[1]._name;
		_topscore[2]._time = _topscore[1]._time;
		
		_topscore[1]._name = name;
		_topscore[1]._time = score;
	
	}
	else if(_topscore[2]._time<score)
	{
		_topscore[2]._name = name;
		_topscore[2]._time = score;
	}
	
	
}

writeTopScore = function(stage)
{
	var topscoreobj = "";

	for(var i=0; i<3; i++)
    {
        for (var imsi in _topscore[i]) {                                          // 파일에 저장하기 위해 Object의 내용을 파해친 후 personObj에 저장
            topscoreobj += _topscore[i][imsi] + '\n';
        }
        
    }             
        
    var fileSystemObj = new FileSystem(); 
    
   	if (!fileSystemObj.isValidCommonPath(curWidget.id)) {
        fileSystemObj.createCommonDir(curWidget.id);}
        
    var fileObj1 = fileSystemObj.openCommonFile(curWidget.id + '/15x15_' + stage + '.data', 'w');   
    
    if(fileObj1.writeAll(topscoreobj))         // Array에서 받아온 것들을 싸그리 모은 personwriteObj를 왕창 저장 완료시 쓴 내용 표시
    {                                             // 쓴 내용을 표시하는 것은 실제 앱 구동에는 필요 없음
        alert("파일 쓰기가 완료 되었습니다");
        alert("-------- 쓰기내용 ---------");
        alert(topscoreobj);
    }
    
    fileSystemObj.closeCommonFile(fileObj1);

    topscoreobj = '';  
}

readTopScore = function(stage)	// 탑 스코어 읽어오기
{
	var fileSystemObj = new FileSystem(); 

    if (!fileSystemObj.isValidCommonPath(curWidget.id)) {     // Common 폴더 없으면 만들어 줍니다.
    fileSystemObj.createCommonDir(curWidget.id);}
    
    if(!(fileSystemObj.openCommonFile(curWidget.id + '/15x15_' + stage + '.data', 'r') == null))   // 처음 이라면 파일이 없을수가 있죠, 그때는 안불러옵니다.
    {
        fileObj = fileSystemObj.openCommonFile(curWidget.id + '/15x15_' + stage + '.data', 'r');  // 파일 오픈하구요.
        
        var i=0;

            for(i=0;i<3;i++)
            {

                _topscore[i]._name = fileObj.readLine();
				_topscore[i]._time = fileObj.readLine();

            }
      
        fileSystemObj.closeCommonFile(fileObj);                      // 당연히 닫아줘야 해용~~ㅋㅋ
        
    }  
                    
}

setItem = function(timeup,hint)
{
	
	switch(timeup)
	{
		case 0: $("#timeupitem").attr("src","resource/images/item0.png"); 	break;
		case 1: $("#timeupitem").attr("src","resource/images/item1.png"); 	break;
		case 2: $("#timeupitem").attr("src","resource/images/item2.png"); 	break;
		case 3: $("#timeupitem").attr("src","resource/images/item3.png"); 	break;
	}
	switch(hint)
	{
		case 0: $("#hintitem").attr("src","resource/images/item0.png"); 	break;
		case 1: $("#hintitem").attr("src","resource/images/item1.png"); 	break;
		case 2: $("#hintitem").attr("src","resource/images/item2.png"); 	break;
		case 3: $("#hintitem").attr("src","resource/images/item3.png"); 	break;
	}
}

setClearImage = function(stage)
{
	$("#clearimage").attr("src","resource/15x15/15x15clear" + stage + ".png"); 
}


 //스테이지 깼는지 확인하는 파일 불러오기
 readFile = function(){

        var fileSystemObj = new FileSystem(); 

        if (!fileSystemObj.isValidCommonPath(curWidget.id)) {     // Common 폴더 없으면 만들어 줍니다.
            fileSystemObj.createCommonDir(curWidget.id);}
    
        //if(fileSystemObj.openCommonFile(curWidget.id + '/Level5.data', 'r')   // 처음 이라면 파일이 없을수가 있죠, 그때는 안불러옵니다.
        //{
			var fileObj3 = fileSystemObj.openCommonFile(curWidget.id + '/Level2.data', 'r');
			
            for(i=0;i<5;i++)
            {
                stageState[i] = fileObj3.readLine();
            }
			      
			fileSystemObj.closeCommonFile(fileObj3);                      // 당연히 닫아줘야 해용~~ㅋㅋ
			
			
			for(i=0;i<5;i++)
            {
                alert(stageState[i] + "\n");
            }     
		//}
}


//깬 스테이지 write        
writeFile = function(mapIndex)
{

	alert("쓰기 들어옴");
	alert(mapIndex);

	readFile();

	var fileSystemObj1 = new FileSystem(); 
	var mapwriteObj='';
    	
	stageState[mapIndex] = 1;
	
	if (!fileSystemObj1.isValidCommonPath(curWidget.id)) {
		fileSystemObj1.createCommonDir(curWidget.id);}
        
	var fileObj1 = fileSystemObj1.openCommonFile(curWidget.id + '/Level2.data', 'w');   
	
	for(i=0; i<5; i++) {
		mapwriteObj += stageState[i] +'\n';;
	alert(mapwriteObj);
	}
	alert("ㅇㅇ");
	if(fileObj1.writeAll(mapwriteObj)) {
		alert("파일 쓰기가 완료 되었습니다");
        alert("-------- 쓰기내용 ---------");
        alert(mapwriteObj);
	}
	else
		alert("실패");
    
    fileSystemObj1.closeCommonFile(fileObj1);

    mapwriteObj = '';  
            
}

// 수진 추가

setStageName = function (stage)
{
	
	switch(stage)
	{
		case '0': document.getElementById("stagename").innerHTML = "앵두"; break;
		case '1': document.getElementById("stagename").innerHTML = "스누피"; break;
		case '2': document.getElementById("stagename").innerHTML = "미키마우스"; break;
		case '3': document.getElementById("stagename").innerHTML = "헬기"; break;
		case '4': document.getElementById("stagename").innerHTML = "삐에로"; break;
	}
}
